package com.example.tiantian.process;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import com.example.tiantian.OnReceiveListener;
import com.example.tiantian.R;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class ProcessWidgetService extends Service implements OnReceiveListener {

    ActivityManager activityManager;
    AppWidgetManager widgetManager;
    ComponentName widget;
    RemoteViews views;
    List<RunningAppProcessInfo> pros;
    ProcessWidgetReceiver receiver;
    boolean isRun = true;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        widgetManager = AppWidgetManager.getInstance(this);
        widget = new ComponentName(this, ProcessWidget.class);
        views = new RemoteViews(getPackageName(), R.layout.widget_process);

        // 实时显示 当期进程数量，可用内存数
        new Thread() {
            public void run() {
                while (isRun) {

                    setText();

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        Log.e(getPackageName(), e.toString());
                    }
                }
            };
        }.start();

        receiver = new ProcessWidgetReceiver();
        receiver.SetOnReceiveListener(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction("action.TIANTIAN_WIDGET_RECEIVER");
        registerReceiver(receiver, filter);

        // 注册 事件
        // 一键清理：服务内注册广播接收器，点击时发送一个广播，接收到广播后 清理所有进程
        Intent intent = new Intent();
        intent.setAction("action.TIANTIAN_WIDGET_RECEIVER");
        PendingIntent pintent = PendingIntent.getBroadcast(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.process_cleaner_clean, pintent);

        // 图标点击 进入应用的某个activity
        Intent intent2 = new Intent(this, ProcessActivity.class);
        PendingIntent pintent2 = PendingIntent.getActivity(this, 200, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.process_cleaner_widget, pintent2);

        widgetManager.updateAppWidget(widget, views);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRun = false;
        unregisterReceiver(receiver);
    }

    // 获取可用内存
    public long getUseableMemory() {
        android.app.ActivityManager.MemoryInfo minfo = new android.app.ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(minfo);
        long size = minfo.availMem;
        return size;
    }

    // 获取总内存大小
    public long getTotalMemory() {
        String filename = "/proc/meminfo";
        String content = "";
        long total = 0;
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(filename));
            content = br.readLine();
            total = Long.parseLong(content.substring(content.indexOf(":") + 1, content.indexOf("k")).trim());
            total *= 1024;
        } catch (FileNotFoundException e) {
            Log.e(getPackageName(), e.toString());
        } catch (IOException e) {
            Log.e(getPackageName(), e.toString());
        }

        return total;
    }

    public void setText() {
        pros = activityManager.getRunningAppProcesses();
        // 设置文本
        views.setTextViewText(R.id.process_cleaner_count,
                getString(R.string.process_cleaner_count) + ":" + pros.size());
        views.setTextViewText(R.id.process_cleaner_memory, getString(R.string.process_cleaner_memory) + ":"
                + (100 - getUseableMemory() * 100 / getTotalMemory()) + "%");

        widgetManager.updateAppWidget(widget, views);

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        for (RunningAppProcessInfo r : pros) {
            if (r.processName.equals(getPackageName())) {
                continue;
            }
            activityManager.killBackgroundProcesses(r.processName);

            // 更新文本显示

            setText();

        }
    }
}
